package com.achao.achaomq.service.impl;

import com.achao.achaomq.constants.RocketMqConstant;
import com.achao.achaomq.exception.CommonException;
import com.achao.achaomq.service.RocketMqService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
@Slf4j
public class RocketMqServiceImpl implements RocketMqService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送rocketMQ消息
     * @param rvo
     * @param topic
     * @param remark
     */
    @Override
    public void sendRocketMQ(Object rvo, String topic, String remark) {
        log.info("RocketMq发送前！");
        if(null != rvo){
            log.info("RocketMQ发送ing....");
            sendMq(rvo,rocketMQTemplate,topic,remark);
        }
        log.info("RocketMq发送后！");
    }

    /**
     * 发送数据
     *
     * @param rvo
     * @param topic
     * @return void
     */
    private void sendMq(Object rvo, RocketMQTemplate rocketMqTemplate, String topic, String msg) {
        SendStatus sendStatus = rocketMqTemplate.syncSend(topic, new GenericMessage<>(rvo), RocketMqConstant.TIMEOUT).getSendStatus();
        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
            throw new CommonException(msg);
        }
    }
}
